package com.ge.med.cchelper.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPInputStream;

import org.xeustechnologies.jtar.TarEntry;
import org.xeustechnologies.jtar.TarInputStream;

public class GZipHelper {

	String gzipFileName = null;

	public GZipHelper(String gzipFileName) {
		this.gzipFileName = gzipFileName;
	}

	public void unTargzFile(String destDir) throws Exception {
		LogUtil.out("[GZIP]attempt to unpack " + gzipFileName);
		FileInputStream fileIn = null;
		BufferedInputStream bufIn = null;
		GZIPInputStream gzipIn = null;
		TarInputStream taris = null;
		try {
			fileIn = new FileInputStream(gzipFileName);
			bufIn = new BufferedInputStream(fileIn);
			gzipIn = new GZIPInputStream(bufIn);
			taris = new TarInputStream(gzipIn);

			TarEntry entry = null;
			while ((entry = taris.getNextEntry()) != null) {
				int count;
				byte data[] = new byte[2048];

				String name = entry.getName();
				String filetemp = destDir + File.separator + name;
				// LogUtil.out("attempt to touch "+name);
				try {
					if (name.endsWith("/")) {
						mkFolder(filetemp);
					} else {
						File file = mkFile(filetemp);
						FileOutputStream fos = new FileOutputStream(file);
						BufferedOutputStream dest = new BufferedOutputStream(
								fos);
						while ((count = taris.read(data)) != -1) {
							dest.write(data, 0, count);
						}

						dest.flush();
						dest.close();
					}
				} catch (Exception e) {
					LogUtil.err("unpack "+filetemp+" faild.\r\n"+e.getMessage());
				}
			}

		} finally {
			taris.close();
			gzipIn.close();
			bufIn.close();
			fileIn.close();
		}
		LogUtil.out("[GZIP]unpack completed.");
	}

	private void mkFolder(String fileName) {
		File f = new File(fileName);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	private File mkFile(String fileName) throws Exception {
		File f = new File(fileName);
		f.createNewFile();

		return f;
	}

	public static void main(String[] strs) {
		try {
			GZipHelper gzip = new GZipHelper(
					"C:\\WorkSpace\\EclipseWorkSpace\\be1\\_ctsys_install.gz");
			gzip.unTargzFile("C:\\WorkSpace\\EclipseWorkSpace\\be1\\");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
